package com.cx.contentcenter.controller;

import com.cx.contentcenter.entity.Share;
import com.cx.contentcenter.entity.User;
import com.cx.contentcenter.entity.dto.ShareUserDto;
import com.cx.contentcenter.feign.UserFeignClient;
import com.cx.contentcenter.service.ShareService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * (Share)表控制层
 *
 * @author ThinkPad
 * @since 2021-09-09 14:58:53
 */
@RestController
@RequestMapping("share")
@Slf4j
public class ShareController {

//    @Resource
//    private RestTemplate restTemplate;

    @Resource
    private UserFeignClient userFeignClient;

    /**
     * 服务对象
     */
    @Resource
    private ShareService shareService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public ShareUserDto selectOne(Integer id) {
        Share share = shareService.queryById(id);
        //1.当前微服务的用户信息
        Integer userId = share.getUserId();

//        //Ribbon负载均衡，直接使用服务名代替uri
//        String userUrl = "http://user-center/user/selectOne/{userId}";
//        User user = restTemplate.getForObject(userUrl, User.class, userId);

        //调用userFeignClient的方法查询用户信息
        User user = userFeignClient.findByUserId(userId);

        log.info("{}"+user.getWxNickname());

        //2.当前微服务请求用户微服务获取到的用户信息，包含【用户的昵称】
        String nickname = user.getWxNickname();

        //3.该Dto主要用来封装：当前微服务的用户信息+用户微服务的用户昵称
        ShareUserDto shareUserDto = new ShareUserDto();
        shareUserDto.setWxNickname(nickname);
        BeanUtils.copyProperties(share, shareUserDto);
        return shareUserDto;
    }


    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        // http://localhost:8081/user/selectOne?id=1
        String userUrl = "http://localhost:8081/user/selectOne?id=1";
        ResponseEntity<User> forEntity = restTemplate.getForEntity(userUrl, User.class);
        System.out.println(forEntity);

        HttpStatus statusCode = forEntity.getStatusCode();
        User body = forEntity.getBody();

        System.out.println(body.getWxId() + ":" + body.getWxNickname());
    }


}